//
//  CartoonMyDownLoadDetailsViewController.m
//  Cartoon
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonMyDownLoadDetailsViewController.h"
#import "CartoonMyDownLoad.h"
#import "CartoonMyDownLoadTableViewCell.h"
#import <ASIHTTPRequest.h>
#import <ASINetworkQueue.h>
#import "CartoonReadingViewController.h"


@interface CartoonMyDownLoadDetailsViewController ()<UITableViewDataSource,UITableViewDelegate,ASIHTTPRequestDelegate,ASIProgressDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *bigArray;
@property (nonatomic, strong) NSMutableDictionary *pictureDic;
@property (nonatomic, strong) NSMutableArray *pictureDicArr;
@property (nonatomic, strong) NSMutableArray *FMDBArray;
@property (nonatomic, strong) NSMutableArray *pictureArr;
@property (nonatomic, strong) NSMutableDictionary *allPictureArrDic;
@property (nonatomic, strong) NSMutableArray *buttonBOOLArray;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) NSInteger cellNum;
@property (nonatomic, strong) ASINetworkQueue *netWorkQueue;

@property (nonatomic, strong) NSMutableArray *tempRequestList;
@property (nonatomic, strong) NSMutableArray *requestUrlArr;
//@property (nonatomic, strong) UIProgressView *progressView;
//@property (nonatomic, strong) UIProgressView *queueProgressView;
//@property (nonatomic, strong) UILabel *label;
//@property (nonatomic, strong) UILabel *queuqLabel;
@end

@implementation CartoonMyDownLoadDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.allPictureArrDic = [NSMutableDictionary dictionary];
    self.buttonBOOLArray = [NSMutableArray array];
    self.requestUrlArr = [NSMutableArray array];
    self.pictureDicArr = [NSMutableArray array];
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49)];
    [self.view addSubview:self.scrollView];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SelfViewWidth, SelfViewHeight - 64 - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[CartoonMyDownLoadTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.scrollView addSubview:_tableView];
    
    ASINetworkQueue *que = [[ASINetworkQueue alloc] init];
    self.netWorkQueue = que;
    [self.netWorkQueue reset];
    self.netWorkQueue.delegate = self;
//    [self.netWorkQueue setDownloadProgressDelegate:_queueProgressView];
    [_netWorkQueue setQueueDidFinishSelector:@selector(queueRequestFinish:)];
    [_netWorkQueue setRequestDidFinishSelector:@selector(requestFinish:)];
    [self.netWorkQueue setShowAccurateProgress:YES];
    

    UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
    label.text = @"您还没有下载章节哦";
    label.textAlignment = NSTextAlignmentCenter;
    label.tag = 101;
    label.hidden = YES;
    label.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:label];

    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"开始下载" style:UIBarButtonItemStylePlain target:self action:@selector(beginButtonAction:)];
  
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonAction)];
    
    [self readingHandler];

    self.cellNum = 0;
//    NSLog(@"%@",_pageArray);
    
}
- (void)backButtonAction
{
    [_netWorkQueue reset];
    [self.navigationController popViewControllerAnimated:YES];
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonBeginButton (button bool , cartoonID text primary key)"]];
        NSLog(@"创建是否成功 : %d",creatResult);
    }
    BOOL btn = NO;
    BOOL btnInsertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into CartoonBeginButton values ('%d','%@')",btn,[NSString stringWithFormat:@"%@",self.comic_id]]];
    
    if (btnInsertResult == YES) {
        NSLog(@"插入成功");
    }else{
        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update CartoonBeginButton set CartoonBeginButton = '%d' where button = '%d' and cartoonID = '%@'",btn,!btn,self.comic_id]];
        NSLog(@"插入失败");
    }
}
- (void)readingHandler
{
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/comicChapterListForIosV2/uin/0/local_version/3.1.0/channel/1001/guest_id/491A80FA-091B-4330-B939-7DE39BB24F7F/comic_id/%@",self.comic_id];
    [NetHandler nilHUDdataWithUrl:str complant:^(id data) {
        NSArray *bigArray = [data objectForKey:@"data"];
        NSMutableArray *array = [NSMutableArray array];
        BOOL isOpen = [[FMDB shareFMDB].db open];
        if (!isOpen) {
            NSLog(@"打开失败");
        }else{
            
            BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonMyDownLoad (name text , image text , cartoonID text primary key , cartoonPage text)"]];
            NSLog(@"创建是否成功 : %d",creatResult);
        }
        self.bigArray = [NSMutableArray array];
        for (NSDictionary *dic in bigArray) {
            [self.bigArray insertObject:dic atIndex:0];
        }
        if (_pageArray == nil) {
           
            FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonMyDownLoad"];
            self.pageArray = [NSMutableArray array];
            
            while ([set next]) {
                CartoonMyDownLoad *down = [[CartoonMyDownLoad alloc]init];
                down.name = [set stringForColumn:@"name"];
                down.cartoonID = [set stringForColumn:@"cartoonID"];
                down.cartoonPage = [set stringForColumn:@"cartoonPage"];
                down.image = [set stringForColumn:@"image"];
                if ([[[down.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.comic_id]) {
                    [self.pageArray addObject:[NSString stringWithFormat:@"%ld",[down.cartoonPage integerValue] - 1]];
                }
                
            }
            for (NSString *str in _pageArray) {
                
                self.pictureDic = [self.bigArray objectAtIndex:[str integerValue]];
                BOOL insertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into CartoonMyDownLoad values ('%@','%@','%@','%@')",self.name,self.myImageUrl,[NSString stringWithFormat:@"%@/%@",[self.pictureDic objectForKey:@"cid"],self.comic_id],[NSString stringWithFormat:@"%ld",[str integerValue] + 1]]];
                
                [array addObject:[self.pictureDic objectForKey:@"cid"]];
                if (insertResult == YES) {
                    NSLog(@"插入成功");
                }else{
                    NSLog(@"插入失败");
                }
            
                [self handler];
            }
            
        }else{
        for (NSString *str in _pageArray) {
           
            self.pictureDic = [self.bigArray objectAtIndex:[str integerValue]];
            BOOL insertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into CartoonMyDownLoad values ('%@','%@','%@','%@')",self.name,self.myImageUrl,[NSString stringWithFormat:@"%@/%@",[self.pictureDic objectForKey:@"cid"],self.comic_id],[NSString stringWithFormat:@"%ld",[str integerValue] + 1]]];
            
            [array addObject:[self.pictureDic objectForKey:@"cid"]];
            if (insertResult == YES) {
                NSLog(@"插入成功");
            }else{
                NSLog(@"插入失败");
            }
        
            [self handler];
        }
        }
        
        FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonMyDownLoad"];
        
        self.FMDBArray = [NSMutableArray array];
        NSMutableArray *setArray = [NSMutableArray array];
        while ([set next]) {
            CartoonMyDownLoad *myDown = [[CartoonMyDownLoad alloc]init];
            myDown.name = [set stringForColumn:@"name"];
            myDown.image = [set stringForColumn:@"image"];
            myDown.cartoonID = [set stringForColumn:@"cartoonID"];
            myDown.cartoonPage = [set stringForColumn:@"cartoonPage"];
            [setArray addObject:myDown];
        }
        
        for (CartoonMyDownLoad *myDown in setArray) {
            for (NSString *cid in array) {
                if ([myDown.cartoonID isEqualToString:[NSString stringWithFormat:@"%@/%@",cid,self.comic_id]]) {
//                    NSLog(@"%@",myDown.cartoonID);
                    [self.FMDBArray addObject:myDown];
                }
            }
        }
        if (_FMDBArray.count == 0 ) {
            [self.view viewWithTag:101].hidden = NO;
        }
        [self.tableView reloadData];
    }];
    
    
}

- (void)handler
{
    NSString *str = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListForIos/comic_id/%@/cid/%@/clientType/0",self.comic_id,[self.pictureDic objectForKey:@"cid"]];
//        NSLog(@"%@",_pictureDic);

    [self.pictureDicArr addObject:_pictureDic];
    [NetHandler nilHUDdataWithUrl:str fileName:[NSString stringWithFormat:@"%@%@",[self.pictureDic objectForKey:@"cid"],self.comic_id] complant:^(id data, NSString *pathName) {
        NSMutableArray *array = [NSMutableArray array];
//        NSLog(@"%@",data);
        for (NSDictionary *dic in [[data objectForKey:@"data"] objectForKey:@"img_infos"]) {
            [array addObject:[dic objectForKey:@"current_img_url"]];
        }
        
        [self.allPictureArrDic setObject:array forKey:pathName];
//        [self ASIHTTPRequestPictureWithPath:pathName urlWithArrayUrl:array];
        //        NSLog(@"%ld",self.allPictureArrArr.count);
        [self.tableView reloadData];
    }];

    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    self.tableView.frame = CGRectMake(0, 0, SelfViewWidth, self.FMDBArray.count * 100);
    self.scrollView.contentSize = CGSizeMake(0, self.FMDBArray.count * 100);
    return self.FMDBArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonMyDownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    CartoonMyDownLoad *down = [self.FMDBArray objectAtIndex:indexPath.row];
    cell.myNameLabel.text = down.name;
    
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:down.image] placeholderImage:[UIImage imageNamed:@"5"]];
    
    cell.myPageLabel.text = [NSString stringWithFormat:@"第%@话",down.cartoonPage];
    
//    NSLog(@"%@",self.allPictureArrArr);
    if (self.allPictureArrDic.count > indexPath.row) {
        self.pictureArr = [self.allPictureArrDic objectForKey:[NSString stringWithFormat:@"%@%@",[[down.cartoonID componentsSeparatedByString:@"/"] firstObject],[[down.cartoonID componentsSeparatedByString:@"/"] lastObject]]];
    }
//    if (self.buttonBOOLArray.count > indexPath.row) {
//        CartoonBeginButton *mybutton = [self.buttonBOOLArray objectAtIndex:indexPath.row];
//        if (mybutton.button) {NSLog(@"11");
//            cell.myBeginButton.titleLabel.text = @"开始";
//            [cell.myBeginButton setTitle:@"开始" forState:UIControlStateNormal];
//        }else{NSLog(@"22");
//            cell.myBeginButton.titleLabel.text = @"暂停";
//            [cell.myBeginButton setTitle:@"暂停" forState:UIControlStateNormal];
//        }
//    }

   
    //    NSLog(@"%@",cell);
    //初始化Documents路径
    
  
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",[[self.pictureDicArr objectAtIndex:indexPath.row] objectForKey:@"cid"],self.comic_id]];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
        [fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    //    NSLog(@"%@",myPath);
    
    NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *str in arr) {
        if ([[[str componentsSeparatedByString:@"."] lastObject] isEqualToString:@"jpg"]) {
            [array addObject:str];
        }
    }
//    NSLog(@"%ld",array.count);
    
    cell.page = array.count;
    
    cell.myNumberLabel.text = [NSString stringWithFormat:@"%ld/%ld",cell.page,self.pictureArr.count];
    if (self.pictureArr.count == array.count) {
        cell.myDownLabel.text = @"100 %";
        cell.over = YES;
        cell.myProgressView.progress = 100;
        
    }else{
        cell.myDownLabel.text = @"0 %";
        cell.over = NO;
        cell.myProgressView.progress = 0;
    }
//    cell.delegate = self;
    return cell;
    
    
}
- (void)beginButtonAction:(UIBarButtonItem *)item
{
//    CartoonMyDownLoadTableViewCell *carCell = (CartoonMyDownLoadTableViewCell *)cell;
//    if ([carCell.myBeginButton.titleLabel.text isEqualToString:@"开始"]) {
//        carCell.myBeginButton.titleLabel.text = @"暂停";
//        [carCell.myBeginButton setTitle:@"暂停" forState:UIControlStateNormal];
//    }else{
//        carCell.myBeginButton.titleLabel.text = @"开始";
//        [carCell.myBeginButton setTitle:@"开始" forState:UIControlStateNormal];
//    }
    

    
    
    if (_pictureDicArr > 0 && _allPictureArrDic.count > 0) {
        
    
    if ([item.title isEqualToString:@"开始下载"]) {
        item.title = @"暂停下载";

        
        _cellNum = 0;
            for (NSInteger i = 0; i < _pictureDicArr.count; i++) {
                NSString *strr = [NSString stringWithFormat:@"%@%@",[[self.pictureDicArr objectAtIndex:i] objectForKey:@"cid"],self.comic_id];
                [self ASIHTTPRequestPictureWithPath:strr urlWithArrayUrl:[self.allPictureArrDic objectForKey:strr]];
                
//                NSLog(@"allPictureArrArr%@",_allPictureArrDic);
//                NSLog(@"%@",[_netWorkQueue operations]);
            }
        
        
        [self.netWorkQueue go];
    }else{
        item.title = @"开始下载";
   
            self.tempRequestList = [NSMutableArray arrayWithArray:[_netWorkQueue operations]];
//        [self.netWorkQueue reset];
        for (ASIHTTPRequest *request in _tempRequestList) {
            [request clearDelegatesAndCancel];
        }
    }
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}



- (void)ASIHTTPRequestPictureWithPath:(NSString *)myPath urlWithArrayUrl:(NSArray *)array
{
    NSIndexPath *index = [NSIndexPath indexPathForItem:self.cellNum inSection:0];
    CartoonMyDownLoadTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
    _cellNum++;
//    NSLog(@"%@",cell);
    //初始化Documents路径
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    //初始化临时文件路径
    NSString *folderPath = [path stringByAppendingPathComponent:myPath];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断temp文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
    if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
        [fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
//    NSLog(@"%@",myPath);
    
    NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
    
//    NSLog(@"%@",arr);
  
    for (NSInteger n = 10; n < array.count + 10; n++) {
        
    NSString *filePath = array[n - 10];
    
    [self.requestUrlArr addObject:array[n - 10]];
        
    NSURL *url = [NSURL URLWithString:filePath];
    
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    
    request.delegate = self;
        
    //初始下载路径
    NSString *str = [NSString stringWithFormat:@"%ld?%@",n,[[filePath componentsSeparatedByString:@"/"] lastObject]];
//        NSLog(@"%@",str);
        NSInteger i = 0;
        for (NSString *arrStr in arr) {
            if ([arrStr isEqualToString:str]) {
                i++;
            }
        }
        if (i == 0) {
            NSString *savePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",str]];
            //    NSLog(@"%@",savePath);
            
            
            NSString *tempPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.temp",str]];
            //    NSLog(@"%@",tempPath);
            // 设置下载路径
            [request setDownloadDestinationPath:savePath];
            
            //设置临时路径
            [request setTemporaryFileDownloadPath:tempPath];
            
            // 设置下载进度条代理
            [request setDownloadProgressDelegate:cell.myProgressView];
            
            // 设置是否支持断点下载
            [request setAllowResumeForFileDownloads:YES];
            
            // 设置基本信息
            [request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:filePath,@"JPG", nil]];
            
            
            // 添加到Queue中
            
            
            [self.netWorkQueue addOperation:request];
        }

    }
}

- (void)requestFinish:(ASINetworkQueue *)queue
{
    
}
- (void)queueRequestFinish:(ASINetworkQueue *)queue
{
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonBeginButton (button bool , cartoonID text primary key)"]];
        NSLog(@"创建是否成功 : %d",creatResult);
    }
    BOOL btn = NO;
    BOOL btnInsertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into CartoonBeginButton values ('%d','%@')",btn,[NSString stringWithFormat:@"%@",self.comic_id]]];
    
    if (btnInsertResult == YES) {
        NSLog(@"插入成功");
    }else{
        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update CartoonBeginButton set button = '%d' where button = '%d' and cartoonID = '%@'",btn,!btn,self.comic_id]];
        NSLog(@"插入失败");
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"开始下载" style:UIBarButtonItemStylePlain target:self action:@selector(beginButtonAction:)];
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
//    NSLog(@"did = %@",[responseHeaders valueForKey:@"Content-Length"]);
//    NSLog(@"contentLength = %f",request.contentLength / 1024.0 / 1024.0);
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    CartoonReadingViewController *reading = [[CartoonReadingViewController alloc] init];
//    
//    NSString *strr = [NSString stringWithFormat:@"%@%@",[[self.pictureDicArr objectAtIndex:indexPath.row] objectForKey:@"cid"],self.comic_id];
//    
//    //初始化Documents路径
//        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
//    //初始化临时文件路径
//    NSString *folderPath = [path stringByAppendingPathComponent:strr];
//    //创建文件管理器
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    //判断temp文件夹是否存在
//    BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
//    if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
//        [fileManager createDirectoryAtPath:folderPath
//               withIntermediateDirectories:YES
//                                attributes:nil
//                                     error:nil];
//    }
//     
//    NSArray *arr = [fileManager directoryContentsAtPath:folderPath];
//    NSMutableArray *array = [NSMutableArray array];
//    for (NSString *str in arr) {
//        if ([[[str componentsSeparatedByString:@"."] lastObject] isEqualToString:@"jpg"]) {
//            [array addObject:str];
//        }
//    }
//    reading.myTitle = [[self.pictureDicArr objectAtIndex:indexPath.row] objectForKey:@"title"];
//    
//    reading.filePictureArray = [NSArray arrayWithArray:array];
//    
//    reading.path = folderPath;
//    
//    [self.navigationController pushViewController:reading animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
